package com.users.rn.common.download

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.text.TextUtils
import com.users.rn.rncommon.download.ALHPluginDownloadService
import com.users.rn.rncommon.download.PluginDownloadProgressListener
import com.users.rn.rncommon.util.ReactUtils
import java.lang.Exception


/**
 * @Description:
 * @Author: bluce
 * @Date: 2020/12/3 17:23
 */
object RNPluginDownloadManager {

    const val TAG: String = "RNPluginDownloadManager"

    private var service: ALHPluginDownloadService? = null

    private val mListeners: MutableList<PluginDownloadProgressListener> = mutableListOf()


    private fun log(msg: String) {
        ReactUtils.log2FileRn(msg)
    }

    private val mConnection: ServiceConnection = object : ServiceConnection {


        override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
            log("onServiceConnected")
            try {
                if (binder == null) {
                    return
                }
                service = (binder as ALHPluginDownloadService.Binder).service
                service?.startSnatchApiThread()
                mListeners.forEach { service?.setRNPluginDownloadListener(it) }
                mListeners.clear()
                log("onServiceConnected startSnatchApiThread")
            } catch (err: Exception) {
                log(err.toString())
            }
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            log("onServiceDisconnected")
            service?.cleanRNPluginDownloadListener()
            service = null
            mListeners.clear()
        }
    }

    fun connect(context: Context, pluginId: String, listener: PluginDownloadProgressListener?) {
        try {
            if (service != null) {
                service?.setRNPluginDownloadListener(listener)
            } else {
                listener?.let { mListeners.add(it) }
            }
            val intent = Intent(context, ALHPluginDownloadService::class.java)
            if (!TextUtils.isEmpty(pluginId)) {
                intent.putExtra("pluginId", pluginId)
            }
            context.bindService(intent, mConnection, Context.BIND_NOT_FOREGROUND)
            context.startService(intent)
        } catch (err: Exception) {
            log(" connect() exception=$err,pluginId=$pluginId")
        }
    }
}
